package com.jf.utils;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.util.HashSet;
import java.util.Objects;
import java.util.Random;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-08-22
 * Time:0:37
 */
public class Music implements Runnable {
    private Player bgm;
    private Player[] players;
    private int bgmIndex;

    public Music() {
        players = new Player[4];
        HashSet<Integer> indexs = new HashSet<>();
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(0, 4);
            while (indexs.contains(index)) {
                index = random.nextInt(0, 4);
            }
            indexs.add(index);
            String path = "/muic/bgm" + (index + 1) + ".mp3";
            try {
                players[i] = new Player(Objects.requireNonNull(getClass().getResourceAsStream(path)));
            } catch (JavaLayerException e) {
                throw new RuntimeException(e);
            }
        }
        bgmIndex = 0;
        bgm = players[bgmIndex];
        try {
            bgm.play();
        } catch (JavaLayerException e) {
            throw new RuntimeException(e);
        }
    }

    private void listening() throws JavaLayerException {
        if (bgm.isComplete()) {
            bgm = players[bgmIndex];
            bgm.play();
            bgmIndex++;
            if (bgmIndex >= 4) bgmIndex = 0;
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                listening();
                Thread.sleep(1000);
            } catch (InterruptedException | JavaLayerException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
